package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.naming.NamingException;

import com.domain.Packages;

public class PackagesDAO extends BaseDAO {
	public int insert(Packages p) {
		int result = 0;
		try {
			Connection conn = getConnection();
			String sql = "insert into packages values(?, ?, ?)";
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.setString(1, p.getPackageId());
			stmt.setString(2, p.getProductId());
			stmt.setInt(3, p.getQuantity());
			result = stmt.executeUpdate();
			conn.close();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public List<Packages> getPackagesByPackageId(String code) {
		List<Packages> list = new LinkedList<Packages>();
		try {
			Connection conn = getConnection();
			String sql = "select * from packages where packageId=?";
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.setString(1, code);
			ResultSet rs = stmt.executeQuery();
			while(rs.next()) { 
				String packageId = rs.getString("packageId");
				String productId = rs.getString("productId");
				int qty = rs.getInt("quantity");
				list.add(new Packages(packageId, productId, qty));
			}
			conn.close();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public void deletePackageByPackageId(String code) {
		try {
			Connection conn = getConnection();
			String sql = "delete from packages where packageid=?";
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.setString(1, code);
			stmt.executeUpdate();		
			conn.close();	
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
